package com.um.springboot.starter.utils;

import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@Slf4j
public class EmailUtil {

	/**
	 * 发送邮件
	 * @param smtp smtp服务器
	 * @param username 用户名
	 * @param password 密码
	 * @param title 邮件标题
	 * @param content 邮件内容
	 * @param from 发送人邮件
	 * @param to 接收人邮件列表，“，”分开
	 * @return
	 */
	public static Boolean sendEmail(String smtp,String display,final String username,final String password,
			String title,String content,String from,String to) {
		
		Properties props = new Properties();
		// 两个属性必须配置
		// 连哪种服务器
		props.setProperty("mail.transport.protocol", "smtp");
		// 设置需要验证(给提供用户名、密码)
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.host",smtp);
		Session session = Session.getInstance(props,
		// 返回验证信息的内部类
				new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username,password);
					}
				}
		);

		//设置自定义发件人昵称 
        String displayName=""; 
        try { 
        	displayName = javax.mail.internet.MimeUtility.encodeText(display); 
        } catch (UnsupportedEncodingException e) { 
            log.error("", e); 
        }
        
		session.setDebug(true);
		Message msg = new MimeMessage(session);
		try {
			msg.setFrom(new InternetAddress(from,displayName));
			msg.setSubject(title);
			msg.setRecipients(RecipientType.TO, InternetAddress.parse(to));
			msg.setContent(content,"text/html;charset=gbk");

			// 没有指定收件人 会在msg里面去找
			Transport.send(msg);
			return true;
		} catch (AddressException e) {
			log.error("", e);
			return false;
		} catch (MessagingException e) {
			log.error("", e);
			return false;
		}catch(UnsupportedEncodingException e){
			log.error("", e);
			return false;
		}
	}
}
